/* 
 * File:   MainProcessQuitHandler.cpp
 * Author: dell
 * 
 * Created on 2012年4月9日, 下午3:12
 */

#include "MainProcessQuitHandler.h"
#include "RapidServer.h"
#include "ServerPid.h"
#include <evhttp/CleanerTimer.h>
#include <evhttp/Dispatcher.h>

namespace Rapid{
    MainProcessQuitHandler::MainProcessQuitHandler(RapidServer* rapidServer): rapidServer(rapidServer), repeat(0) {
    }

    MainProcessQuitHandler::~MainProcessQuitHandler() {
    }

    bool MainProcessQuitHandler::onProcessSignalEvent(const ProcessSignalEvent* e){
//        LOG_DEBUG("main, stop server, signal:%d, repeat:%d, allRapidServers.size:%d", e->signal, repeat, allRapidServers.size());
        if(repeat == 0){
            executeClose();
        }        
        return true;
    }
    
    
    bool MainProcessQuitHandler::onTimerEvent(const TimerEvent* e){
        float t = (MAX_WAIT_QUIT_TIME-MAX_WAIT_QUIT_INTERVAL*repeat);
//        printf("stopping server, after %f seconds enforce stop\n", (t>0?t:0));
        executeClose();
        return true;
    }      
  
    
    void MainProcessQuitHandler::executeClose(){
        LOG_DEBUG("(MAX_WAIT_QUIT_TIME/MAX_WAIT_QUIT_INTERVAL):%f, repeat:%d", (MAX_WAIT_QUIT_TIME/MAX_WAIT_QUIT_INTERVAL), repeat);
        notifyClose();
        CleanerTimer::instance.cleanupAll();
        if(isClosed() || repeat > (int)(MAX_WAIT_QUIT_TIME/MAX_WAIT_QUIT_INTERVAL)){
            ServerPid serverPid(rapidServer->getHomeDir(), rapidServer->getServerPort());
            serverPid.remove();
        
            printf("succeed stop server at port %d\n", rapidServer->getServerPort());
            Timer::stop();
            if(rapidServer->httpServer){
                rapidServer->httpServer->getDispatcher()->killProcesses();
                rapidServer->httpServer->stop();
            }
            CleanerTimer::instance.stop();
            ProcessSignal::stop();
            exit(0);
            return;
        }
        repeat++;
        Timer::start(MAX_WAIT_QUIT_INTERVAL);
    }

    void MainProcessQuitHandler::notifyClose(){
        LOG_DEBUG("");
        if(rapidServer->httpServer){
            rapidServer->httpServer->getDispatcher()->notifyCloseProcesses();
        }
    }

    bool MainProcessQuitHandler::isClosed(){
        LOG_DEBUG("");
        return !rapidServer->httpServer || rapidServer->httpServer->getDispatcher()->processesCount() <= 0;
    }
    
    
}

